﻿@using System.ComponentModel
@using System.Net.Http.Headers


@page "/admin/categories"
@layout AdminLayout

@* 依赖注入 *@
@inject HttpClient Http
@inject IJSRuntime JSRuntime
@inject MessageService _message
@inject NavigationManager navigationManager


<PageTitle>分类列表</PageTitle>


@* 面包屑 *@
<Breadcrumb Style="margin: 16px 0;">
    <BreadcrumbItem>admin</BreadcrumbItem>
    <BreadcrumbItem>catelist</BreadcrumbItem>
</Breadcrumb>
<Content Class="site-layout-background" Style=" padding: 0px; margin: 0; min-height: 280px;">

    <div>
        <p style="color: darkblue;margin-bottom: 10px;font-size: 16px;font-weight:400;">分类列表</p>
        @*添加按钮*@
        <Button Type="@ButtonType.Primary" Icon="@IconType.Outline.PlusSquare" OnClick="@ShowModal">添加分类</Button>

        @*添加分类弹窗*@
        <Modal Title="添加分类" Visible="@_visible" OnOk="@HandleOk" OnCancel="@HandleCancel"
            ConfirmLoading="@_confirmLoading">
            <Input @bind-Value="@_addFormValue" placeholder="请输入分类名称" />
        </Modal>

        @*显示表格*@
        <Table Bordered=@true Size=@TableSize.Middle TItem="Category" DataSource="@_categories"
            @bind-PageIndex="_pageIndex" @bind-PageSize="_pageSize" Total="_total" Loading="_loading" RemoteDataSource
            style="margin-top: 10px;">

            <Column @bind-Field="@context.Id"></Column>
            <Column @bind-Field="@context.Name"></Column>

            <ActionColumn Title="操作">
                <Space Size=@("middle")>
                    <SpaceItem>
                        <Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Edit"
                            OnClick="()=>Edit(context.Id)">编辑</Button>
                    </SpaceItem>
                    <SpaceItem>
                        <Popconfirm Placement="@Placement.Top" Title="确定删除吗？" OkText="确定" CancelText="取消"
                            OnConfirm="()=>Confirm(context.Id)">
                            <Button Danger Icon="@IconType.Outline.Delete">删除</Button>
                        </Popconfirm>
                    </SpaceItem>
                </Space>
            </ActionColumn>

        </Table>
    </div>

</Content>


@code {
    private bool _loading = false; //是否加载状态
    private int _pageIndex = 1; //当前页码
    private int _pageSize = 20; //页大小
    private int _total; //总记录数

    private bool _visible = false; //添加表单是否显示
    private string _addFormValue = ""; //添加分类时接收分类名称
    private bool _confirmLoading = false; //询问框加载状态

    //接收后端数据
    IEnumerable<Category> _categories = new List<Category>();


    public class Category
    {
        [DisplayName("ID")]
        public int Id { get; set; }

        [DisplayName("名称")]
        public string Name { get; set; }

        //[DisplayName("创建时间")]
        //public string Create_at { get; set; }

    }

    /// <summary>
    /// 接收响应数据，List<T>
    /// </summary>
    public class RespData<T> where T : new()
    {
        public int Code { get; set; }
        public string Msg { get; set; }
        public List<T> Data { get; set; } = new List<T>();
    }

    /// <summary>
    /// 接收响应数据，T
    /// </summary>
    public class RespData2<T> where T : new()
    {
        public int Code { get; set; }
        public string Msg { get; set; }
        public T Data { get; set; } = new T();
    }


    /// <summary>
    /// 初始化加载
    /// </summary>
    /// <returns></returns>
    protected override async Task OnInitializedAsync()
    {
        //获取数据
        await GetData();
        await base.OnInitializedAsync();
    }


    // /// <summary>
    // /// 表格分页改变事件
    // /// </summary>
    // /// <param name="queryModel"></param>
    // /// <returns></returns>
    //async Task HandleTableChange(QueryModel<Category> queryModel)
    //{
    // Console.WriteLine(queryModel);

    // _loading = true;

    // var cateRes = await Http.GetFromJsonAsync<RespData<Category>>("/api/categories");
    // _categories = cateRes.Data;

    // _loading = false;
    // _total = _categories.Count();
    //}



    /// <summary>
    /// 显示添加分类对话框
    /// </summary>
    private void ShowModal()
    {
        _visible = true;
    }

    /// <summary>
    /// 处理添加确认事件
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    private async Task HandleOk(MouseEventArgs e)
    {
        _confirmLoading = true;
        StateHasChanged();

        var requestMessage = new HttpRequestMessage()
        {
            Method = new HttpMethod("POST"),
            RequestUri = new Uri($"{Utils.BASE_URL}/api/category"),
            Content = JsonContent.Create(new Category { Name = _addFormValue }),
        };

        // 获取浏览器localStorage存储的token
        LocalStorageHelper localStorageHelper = new LocalStorageHelper(JSRuntime);
        string token = await localStorageHelper.GetLocalStorage("token");
        // Console.WriteLine("token: " + token);
        // 判断是否有token
        if (!string.IsNullOrEmpty(token))
        {
            // 添加token到请求头
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue(token);
            // 发出请求
            var response = await Http.SendAsync(requestMessage);
            // Console.WriteLine(response);
            // var responseStatusCode = response.StatusCode;
            // Console.WriteLine(responseStatusCode);

            // 读取响应并反序列化
            var resData = await response.Content.ReadFromJsonAsync<RespData2<Category>>();
            // Console.WriteLine(resData);

            if (resData != null && resData.Code != 200) // 添加失败
            {
                _message.Error("分类添加失败");
                _message.Error(resData.Msg);
            }
            else
            {
                _addFormValue = "";
                _visible = false;
                _message.Success("分类添加成功");
                // 刷新表格数据
                await GetData();
            }
            _confirmLoading = false;
        }
        else
        {
            _confirmLoading = false;
            _message.Info("未登录，请登录后再试");
            // 重定向到登录页
            navigationManager.NavigateTo("/admin/login", true);
        }
    }


    /// <summary>
    /// 处理添加取消事件
    /// </summary>
    /// <param name="e"></param>
    private void HandleCancel(MouseEventArgs e)
    {
        _visible = false;
    }

    /// <summary>
    /// 删除确认事件
    /// </summary>
    /// <param name="id"></param>
    private async Task Confirm(int id)
    {
        // Console.WriteLine(id);
        var requestMessage = new HttpRequestMessage()
        {
            Method = new HttpMethod("DELETE"),
            RequestUri = new Uri($"{Utils.BASE_URL}/api/category/{id}"),
        };

        // 获取浏览器localStorage存储的token
        LocalStorageHelper localStorageHelper = new LocalStorageHelper(JSRuntime);
        string token = await localStorageHelper.GetLocalStorage("token");

        // 判断是否有token
        if (!string.IsNullOrEmpty(token))
        {
            // 添加token到请求头
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue(token);
            // 发出请求
            var response = await Http.SendAsync(requestMessage);

            // 读取响应并反序列化
            var resData = await response.Content.ReadFromJsonAsync<RespData2<Category>>();

            if (resData != null && resData.Code != 200) // 删除失败
            {
                _message.Error("分类删除失败");
                _message.Error(resData.Msg);
            }
            else
            {
                _message.Success("分类删除成功");
                // 刷新表格数据
                await GetData();
            }
        }
        else
        {
            _message.Info("未登录，请登录后再试");
            // 重定向到登录页
            navigationManager.NavigateTo("/admin/login", true);
        }
    }


    /// <summary>
    /// 编辑确认事件
    /// </summary>
    /// <param name="id"></param>
    private async Task Edit(int id)
    {
        _confirmLoading = true;
        StateHasChanged();

        var requestMessage = new HttpRequestMessage()
        {
            Method = new HttpMethod("PUT"),
            RequestUri = new Uri($"{Utils.BASE_URL}/api/category/{id}"),
            Content = JsonContent.Create(new Category { Name = _addFormValue }),
        };

        // 获取浏览器localStorage存储的token
        LocalStorageHelper localStorageHelper = new LocalStorageHelper(JSRuntime);
        string token = await localStorageHelper.GetLocalStorage("token");
        // 判断是否有token
        if (!string.IsNullOrEmpty(token))
        {
            // 添加token到请求头
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue(token);
            // 发出请求
            var response = await Http.SendAsync(requestMessage);

            // 读取响应并反序列化
            var resData = await response.Content.ReadFromJsonAsync<RespData2<Category>>();

            if (resData != null && resData.Code != 200) // 添加失败
            {
                _message.Error("分类修改失败");
                _message.Error(resData.Msg);
            }
            else
            {
                _addFormValue = "";
                _visible = false;
                _message.Success("分类修改成功");
                // 刷新表格数据
                await GetData();
            }
            _confirmLoading = false;
        }
        else
        {
            _confirmLoading = false;
            _message.Info("未登录，请登录后再试");
            // 重定向到登录页
            navigationManager.NavigateTo("/admin/login", true);
        }
    }


    /// <summary>
    /// 获取数据方法
    /// </summary>
    /// <returns></returns>
    private async Task GetData()
    {
        _loading = true;

        var cateRes = await Http.GetFromJsonAsync<RespData<Category>>("/api/categories");
        if (cateRes != null && cateRes.Data != null)
        {
            _categories = cateRes.Data;
        }

        _loading = false;
        _total = _categories.Count();
    }
}